﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;

namespace WowGuildSite.Armory
{
    public enum IconType
    {
        Race,
        Gender,
        Faction,
        Class,
        Talent,
        Item,
        Misc,
    }

    public class ArmoryIcon : ArmoryBase
    {
        private IconType        type;
        private object          id;

        public Bitmap           GetIconData(int width, int height)
        {
            // Find the first icon thats greater or equal in size to the 
            // requested size:
            IList<Bitmap>   iconData        = Accessor.DataSource.GetIconData(type,id);
            int             distance        = int.MaxValue;
            Bitmap          closestMatch    = null;

            foreach (Bitmap b in iconData)
            {
                if (b.Width >= width && b.Height >= height)
                {
                    int newDistance = (b.Width - width) * (b.Height * height);
                    if (newDistance < distance)
                    {
                        distance = newDistance;
                        closestMatch = b;
                    }
                }
            }

            if (closestMatch == null)
            {
                // Now disregard that the result can be a smaller icon, we allow upsizing as a fallback:
                foreach (Bitmap b in iconData)
                {               
                    int newDistance = (int)(Math.Abs(b.Width - width) * Math.Abs(b.Height * height));
                    if (newDistance < distance)
                    {
                        distance = newDistance;
                        closestMatch = b;
                    }                  
                }
            }

            if (closestMatch != null)
            {
                if (closestMatch.Width == width && closestMatch.Height == height)
                {
                    return closestMatch;
                }
                else
                {
                    // Resize it:
                    return new Bitmap(closestMatch, new Size(width, height));
                }
            }
            return null;
        }

        internal ArmoryIcon(  ArmoryAccessor accessor, 
                            IconType type,object id )
            : base(accessor)
        {
            if (id == null )
            {
                throw new ArgumentNullException("id");
            }

            this.id     = id;
            this.type   = type;
        }
    }
}
